﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Raven.Client.Document;

namespace NewsCrawler.Common.Models
{
    public abstract class BaseArticle
    {
        public string Id { get { return Url.GetHashCode().ToString(); } }
        public string Summary { get; set; }
        public string Content { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public Category Category { get; set; }
        public DateTime PublishDate { get; set; }
        private List<string> _tags;
        public List<string> Tags
        {
            get { return _tags ?? (_tags = new List<string>()); }
            set { _tags = value; }
        }

        public int ViewCount { get; set; }
        public Publisher Publisher { get; set; }
        public string CultureCode { get; set; }
        public string Url { get; set; }
        private List<string> _images;
        public List<string> Images
        {
            get { return _images ?? (_images = new List<string>()); }
            set { _images = value; }
        }

        public abstract void Parse();

        protected abstract string Folder { get; }

        public string GetImagePath()
        {
            var path = Path.Combine(Environment.CurrentDirectory, "images", Folder);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }

        public void WriteToDB()
        {
            //Database.Open().Articles.Insert(new {Content = this.Content });
            //var db = Database.OpenNamedConnection("DefaultConnectionString");

            var store = new DocumentStore { Url = "http://localhost:8082" };
            store.Initialize();

            using (var session = store.OpenSession())
            {
                Article article = session.Load<Article>(this.Id);
                if (article == null)
                {
                    session.Store(this);
                    session.SaveChanges();
                }
            }
        }
    }
}
